import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { fileURLToPath, URL } from "node:url";
import colors from "picocolors";
import { LoggerWarnOptions } from "sass";
import AutoImport from "unplugin-auto-import/vite";
import IconifyResolver from "unplugin-icons/resolver";
import Iconify from "unplugin-icons/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import { ConfigEnv, loadEnv, UserConfig } from "vite";
import { createHtmlPlugin } from "vite-plugin-html";
import { mars3dPlugin } from "vite-plugin-mars3d";
import vueDevTools from "vite-plugin-vue-devtools";
import svgLoader from "vite-svg-loader";
import { createConfigPlugin } from "./build/config";
import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from "./build/constants";
import pkg from "./package.json";

export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);

  const { VITE_PORT, VITE_PUBLIC_PATH } = env;
  const isBuild = command === "build";

  const pp = VITE_PUBLIC_PATH.endsWith("/") ? VITE_PUBLIC_PATH : `${VITE_PUBLIC_PATH}/`;
  const configFile = `${pp}${GLOB_CONFIG_FILE_NAME}?v=${pkg.version}-${new Date().getTime()}`;

  return {
    base: VITE_PUBLIC_PATH,
    css: {
      preprocessorOptions: {
        scss: {
          api: "modern-compiler",
          logger: {
            warn: (message: string, options: LoggerWarnOptions) => {
              if (options.deprecation) return;
              console.warn("💀 " + colors.yellow(`[scss]: ${message}`));
            },
          },
        },
      },
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        "#": fileURLToPath(new URL("./types", import.meta.url)),
      },
    },
    server: {
      host: true,
      port: +VITE_PORT || 80,
      proxy: {
        "/dev": {
          target: "http://localhost:8000",
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(/^\/dev/, ""),
          secure: false, // 如果是https接口，需要配置这个参数
        },
      },
    },
    build: {
      outDir: OUTPUT_DIR,
      assetsInlineLimit: 4096,
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: false, // 生产环境自动去除 console
          drop_debugger: true, // 生产环境自动去除 debugger
        },
      },
    },
    optimizeDeps: {
      include: ["kml-geojson"],
    },
    plugins: [
      vue(),
      vueJsx(),
      svgLoader(),
      vueDevTools(),
      AutoImport({ resolvers: [ElementPlusResolver()] }),
      Components({ resolvers: [IconifyResolver(), ElementPlusResolver()] }),
      Iconify({ jsx: "react", compiler: "vue3" }),
      mars3dPlugin(),
      createHtmlPlugin({
        minify: isBuild,
        inject: {
          data: { title: env.VITE_GLOB_APP_TITLE },
          tags: isBuild ? [{ tag: "script", attrs: { src: configFile } }] : [],
        },
      }),
      createConfigPlugin(isBuild, env),
    ],
  };
};
